package es.uab.sound;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.Random;

import org.achartengine.GraphicalView;

import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import es.uab.sound.graph.LineGraph;
import es.uab.sound.graph.PointTime;
import es.uab.sound.utils.Settings;

public class RecordActivityTest extends Activity {

	private LineGraph graph = new LineGraph();
	private GraphicalView chartView;

	private Settings settings;

	private TextView valueDB;
	private TextView valueMax;
	private TextView valueMin;
	private Button button;

	private final String startRecordingLabel = "Start Recording";
	private final String stopRecordingLabel = "Stop Recording";
	private boolean mIsRecording = false;
	private ProgressBar mProgressBar;

	//Temporal Variables
	private double dbs = 0.0;
	private double maxdbs = 0.0;
	private double mindbs = 0.0;
	private boolean beginMaxMin;

	private Thread noise = new Thread();

	@Override
	public void onBackPressed() {
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.record, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_settings:
			destroyRecording();
			Intent myIntent = new Intent(RecordActivityTest.this, SettingsActivity.class);
			startActivity(myIntent);
			return true;
		case R.id.action_exit:
			destroyRecording();
			exit();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	public void destroyRecording() {
		button.setText(startRecordingLabel);
		mIsRecording = false;
		noise.interrupt();
		noise = null;
	}

	public void exit() {
		this.finish();
		Intent intent = new Intent(Intent.ACTION_MAIN);
		intent.addCategory(Intent.CATEGORY_HOME);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(intent);
	}

	public void initComponents() {
		mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
		valueDB = (TextView) findViewById(R.id.valueDBs);
		valueMax = (TextView) findViewById(R.id.valueMax);
		valueMin = (TextView) findViewById(R.id.valueMin);
		button = (Button) findViewById(R.id.buttonRec);
		settings = new Settings(this);
	}

	final Handler mHandler = new Handler();
	final Runnable updater = new Runnable() {
		public void run() {
			BigDecimal bd = new BigDecimal(dbs).setScale(settings.getDecimals(), RoundingMode.HALF_UP);
			if (beginMaxMin) {
				if (dbs < mindbs) {
					mindbs = dbs;
					valueMin.setText("MIN: " + bd.toString() + " dBs");
				}
				if (dbs > maxdbs) {
					maxdbs = dbs;
					valueMax.setText("MAX: " + bd.toString() + " dBs");
				}
			} else {
				maxdbs = dbs;
				mindbs = dbs;
			}
			valueDB.setText(bd.toString() + " dBs");
			//valueDB.setTextColor(Color.RED);
			graph.add(new PointTime(new Date(), dbs));
			chartView.repaint();
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_record);
		initComponents();

		mProgressBar.setMax(140);
		button.setText(startRecordingLabel);

		button.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(final View v) {
				if (!mIsRecording) {
					button.setText(stopRecordingLabel);
					mIsRecording = true;
					startBufferedWrite();
				} else {
					button.setText(startRecordingLabel);
					mIsRecording = false;
				}
			}
		});
	}

	private void startBufferedWrite() {
		noise = new Thread(new Runnable() {
			@Override
			public void run() {
				int index = 0;
				try {
					while (mIsRecording) {
						dbs = 40 + (new Random()).nextInt(60) + (new Random()).nextDouble();
						mProgressBar.setProgress((int) dbs);
						mHandler.post(updater);
						Thread.sleep(250);
						index++;
						if (index > 4)
							beginMaxMin = true;
					}

				} catch (Exception e) {
					Toast.makeText(RecordActivityTest.this, e.getMessage(), Toast.LENGTH_SHORT).show();
				} finally {
					mProgressBar.setProgress(0);
				}
			}
		});

		noise.start();
	}

	@Override
	protected void onStart() {
		super.onStart();
		chartView = graph.getView(this);
		LinearLayout layout = (LinearLayout) findViewById(R.id.chart);
		layout.setBackgroundColor(Color.parseColor("#fff3f3f3"));
		layout.addView(chartView, new LayoutParams(LayoutParams.MATCH_PARENT, 300));
		chartView.repaint();
	}
}
